package com.graduation.roombooking.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.roombooking.dto.AppletTimeList;
import com.graduation.roombooking.dto.AppletTimeListDTO;
import com.graduation.roombooking.dto.RoomListDTO;
import com.graduation.roombooking.mapper.EquipmentMapper;
import com.graduation.roombooking.mapper.OrderMapper;
import com.graduation.roombooking.mapper.RoomMapper;
import com.graduation.roombooking.pojo.Equipment;
import com.graduation.roombooking.pojo.Order;
import com.graduation.roombooking.pojo.OrderEquipment;
import com.graduation.roombooking.service.IOrderEquipmentService;
import com.graduation.roombooking.service.IOrderService;
import com.graduation.roombooking.vo.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoXinyi
 * @since 2022-05-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    public static final String STANDARD_FORMAT = "yyyy-MM-dd";
    public static final String TIME="08:00-10:00,10:00-12:00,12:00-14:00,14:00-16:00,16:00-18:00,18:00-20:00,20:00-22:00,22:00-24:00";

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private IOrderEquipmentService orderEquipmentService;
    @Autowired
    private EquipmentMapper equipmentMapper;

    @Override
    public RespBean getList(String companyName) {
        return RespBean.success(orderMapper.getList(companyName));
    }

    @Override
    public RespBean updateStatus(String companyName, Integer status, String orderId) {
        //从数据库里面获取当前状态
        //0取消预约，1拒绝申请， 4审核中  2进行中，3已完成，
        int currentStatus=orderMapper.getStatusById(orderId);
        int row=0;
        switch (currentStatus){
            case 4:
                //审核中->拒绝申请，同意申请，取消预约
                if(status==2 || status==1 || status==0){
                    row=orderMapper.updateStatus(companyName,status,orderId);
                }else {
                    return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION);
                }
                break;
            case 2:
                if(status==3){
                    row=orderMapper.updateStatus(companyName,status,orderId);
                }else{
                    return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION);
                }
                break;
            default:
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"订单已完成，不可修改");
        }

        if(row<1){
            return RespBean.error(RespBeanEnum.UPDATE_ERROR,"修改失败");
        }
        return RespBean.success();
    }

    @Override
    public RespBean unionQuery(UnionQueryOrderVo unionQueryOrderVo, String companyName) {
        return RespBean.success(orderMapper.unionQuery(unionQueryOrderVo,companyName));
    }

    @Override
    public RespBean appoint(AppointRoomVo appointRoomVo, Long phone) {
        //根据roomId获取到价格
        RoomListDTO room=roomMapper.getRoomById(appointRoomVo.getRoomId());
        int flag=room.getRoomUse();
        int status=room.getStatus();
//        int num=room.getNum();
        //这个flag判断应该是去订单表里面找该天该时间段是否有预约订单(status 2和4 表示订单进行中)
        Date day=appointRoomVo.getOpenDate();
        String time=appointRoomVo.getTime();
        try{
            List<Order> orders=orderMapper.getOrderByOpenDateAndTime(day,time);

            if(orders!=null && orders.size()>0){
                return RespBean.error(RespBeanEnum.NO_OPERATION_PERMISSION,"该时间段已被已被预约，请选择其他时间！");
            }
            //判断会议室状态
            if(flag!=0 ){
                return RespBean.error(RespBeanEnum.NO_OPERATION_PERMISSION,"该会议室正在使用中！");
            }
            if(status==0){
                return RespBean.error(RespBeanEnum.NO_OPERATION_PERMISSION,"该会议室禁用！");
            }

            Order order=new Order();
            order.setOpenDate(appointRoomVo.getOpenDate());
            order.setTime(appointRoomVo.getTime());
            order.setRoomId(appointRoomVo.getRoomId());
            order.setTag(appointRoomVo.getTag());
            order.setLinkman(appointRoomVo.getLinkman());
            order.setPhone(String.valueOf(phone));
            order.setStatus(4);
            order.setPrice(room.getPrice());

            //直接将基本信息做插入
            int row=orderMapper.appoint(order);
            if(row<1){
                return RespBean.error(RespBeanEnum.INSERT_ERROR,"预约失败，请尝试刷新页面");
            }
            int orderId=order.getId();
            System.out.println("orderID="+orderId);
            //做设备的插入
            ArrayList<AppointEquipmentVo> appointEquipmentVos=appointRoomVo.getAppointEquipmentVos();
            if(null!=appointEquipmentVos && !appointEquipmentVos.isEmpty()){

                ArrayList<OrderEquipment> orderEquipments=new ArrayList<>();
                for(AppointEquipmentVo vo:appointEquipmentVos){

                    Equipment equipment=equipmentMapper.selectById(vo.getEquipmentId());
                    if(null!=equipment){
                        if(equipment.getNumber()<vo.getNumber()){
                            return RespBean.error(RespBeanEnum.NO_OPERATION_PERMISSION,"申请设备（"+equipment.getName()+"）库存不足，请刷新后重试");
                        }
                        OrderEquipment oe=new OrderEquipment();
                        oe.setOrderId(orderId);
                        oe.setEquipmentId(vo.getEquipmentId());
                        oe.setNumber(vo.getNumber());

                        orderEquipments.add(oe);
                    }else {
                        return RespBean.error(RespBeanEnum.NO_OPERATION_PERMISSION,"该设备不存在");
                    }


                }

                //做订单设备的批量插入
                if(null!=orderEquipments && !orderEquipments.isEmpty()){
                    orderEquipmentService.saveBatch(orderEquipments);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }



//        将该room状态设为使用中（此处需要设置一个定时器，当订单状态完成，自动更改订单状态）
//        if(roomMapper.appletUpdateInUse(appointRoomVo.getRoomId())<1){
//            return RespBean.error(RespBeanEnum.INSERT_ERROR,"预约失败，请尝试刷新页面");
//        }

        return RespBean.success();
    }

    @Override
    public RespBean getTimeList(Integer roomId) {
        //获取全部时间段
        List<String> times=Arrays.asList(TIME.split(","));

        //获取订单中近七天的预约情况
        List<AppletTimeListDTO> timeListDTOS=orderMapper.getTimeList();
        List<AppletTimeList> appletTimeLists=new ArrayList<>();

        //获取当前时间的小时数
        Integer hour=new DateTime().getHourOfDay();
        //当天另做处理
        String day01=new DateTime(timeListDTOS.get(0).getDay()).toString(STANDARD_FORMAT);
        String time01=timeListDTOS.get(0).getTime();
        appletTimeLists.add(new AppletTimeList(day01,removeCurrentTime(hour,times,time01)));


        for(int i=1;i<timeListDTOS.size();i++){
            AppletTimeList appletTimeList=new AppletTimeList();
            //将日期转化为字符串
            DateTime dateTime = new DateTime(timeListDTOS.get(i).getDay());
            //将日期存入
            appletTimeList.setDay(dateTime.toString(STANDARD_FORMAT));

            //将时间存入
            if(timeListDTOS.get(i).getTime()!=null){
                List<String> timeList= Arrays.asList(timeListDTOS.get(i).getTime().split(","));
                //取差集
                appletTimeList.setTime(times.stream().filter(item -> !timeList.contains(item)).collect(toList()));
            }else{
                    appletTimeList.setTime(times);
            }
            appletTimeLists.add(appletTimeList);
        }

        return RespBean.success(appletTimeLists);
    }

    @Override
    public RespBean cancelOrder(Integer orderId, Long phone) {

        Order order=null;
        //首先判断当前订单状态是否可以改变
        try{
             order=orderMapper.getInfoById(orderId);
        }catch (Exception e){
            e.printStackTrace();
        }
//        Order order=orderMapper.selectById(orderId);
        if(order!=null){
            if(!order.getPhone().equals(String.valueOf(phone))){
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"非该用户订单，不可更改");
            }
//0取消预约，1拒绝申请，2进行中，3已完成，4审核中
            if(order.getStatus().equals(0)){
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"订单已取消，不可重复取消");
            }
            if(order.getStatus().equals(1)){
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"订单被拒绝，不可取消");
            }
            if(order.getStatus().equals(2)){
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"订单已进行，不可取消");
            }
            if(order.getStatus().equals(3)){
                return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"订单已完成，不可取消");
            }
            if(order.getStatus().equals(4)){
               int row=orderMapper.cancelOrder(orderId);
               if(row<1){
                   return RespBean.error(RespBeanEnum.UPDATE_ERROR,"取消失败");
               }
               return RespBean.success();
            }
        }

        return RespBean.error(RespBeanEnum.ILLEGAL_OPERATION,"不存在该订单");
    }

    @Override
    public RespBean getPersonalOrder(PersonalOrderVo personalOrderVo, Long phone) {
        return RespBean.success(orderMapper.getPersonalOrder(personalOrderVo,phone));
    }

    @Override
    public RespBean getStatistics(String companyName,Integer day) {
        return RespBean.success(orderMapper.getStatistics(companyName,day));
    }

    public static List<String> removeCurrentTime(Integer hour,List<String>times,String time01){
        //将在工作期间的时间设为已预约时间
        java.util.ArrayList<String> orderTimes=new ArrayList<>();
//        java.util.ArrayList<String> stringList = new ArrayList<>(str.length);
//        Collections.addAll(stringList,str);
        if(null!=time01){
//            orderTimes=Arrays.asList(time01.split(","));//Arrays.asList生成一个固定长度的数组，所以不可使用add方法
            Collections.addAll(orderTimes,time01.split(","));
        }

        Integer count=0;
        if(hour.equals(8)||hour.equals(9)){
            count=1;
        }
        if(hour.equals(10)||hour.equals(11)){
            count=2;
        }
        if(hour.equals(12)||hour.equals(13)){
            count=3;
        }
        if(hour.equals(14)||hour.equals(15)){
            count=4;
        }
        if(hour.equals(16)||hour.equals(17)){
            count=5;
        }
        if(hour.equals(18)||hour.equals(19)){
            count=6;
        }
        if(hour.equals(20)||hour.equals(21)){
            count=7;
        }
        if(hour.equals(22)||hour.equals(23)) {
            count=8;
        }

        for(int i=0;i<count;i++){
            try{
                String time=times.get(i);
                orderTimes.add(time);
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
        if(null!=orderTimes){
            List<String> finalOrderTimes = orderTimes;
            return times.stream().filter(item -> !finalOrderTimes.contains(item)).collect(toList());
        }else {
            return times;
        }

    }
}
